using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Price;
using B.S.NewMedical.Api.Read.DTOS.Price;
using B.S.NewMedical.Domain.Appointment;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Price
{
    /// <summary>
    /// 获取价格服务类型处理器
    /// </summary>
    public class GetPriceServiceTypesHandler : IRequestHandler<GetPriceServiceTypesCommand, ApiResult<List<PriceServiceTypeDto>>>
    {
        private readonly IBaseRepository<PriceServiceType> _serviceTypeRepository;
        private readonly ILogger<GetPriceServiceTypesHandler> _logger;
        private readonly IMapper _mapper;

        public GetPriceServiceTypesHandler(
            IBaseRepository<PriceServiceType> serviceTypeRepository,
            ILogger<GetPriceServiceTypesHandler> logger,
            IMapper mapper)
        {
            _serviceTypeRepository = serviceTypeRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<PriceServiceTypeDto>>> Handle(GetPriceServiceTypesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取价格服务类型列表，科室ID：{DeptId}，医生级别：{DoctorLevel}", 
                    request.DeptId, request.DoctorLevel);

                // 构建基础查询
                var query = _serviceTypeRepository.GetAll().Where(st => !st.IsDeleted);

                // 按科室ID筛选
                if (request.DeptId.HasValue)
                {
                    query = query.Where(st => st.DeptId == request.DeptId.Value);
                }

                // 按医生级别筛选
                if (!string.IsNullOrEmpty(request.DoctorLevel))
                {
                    query = query.Where(st => st.DoctorLevel == request.DoctorLevel);
                }

                // 执行查询
                var serviceTypes = await query.ToListAsync(cancellationToken);

                // 映射到DTO
                var result = serviceTypes.Select(st => new PriceServiceTypeDto
                {
                    Id = st.Id,
                    Name = st.Name,
                    DeptId = st.DeptId,
                    DeptName = GetDepartmentName(st.DeptId), // 这里应该从科室表获取名称
                    DoctorLevel = st.DoctorLevel,
                    Remark = st.Remark
                }).ToList();

                return new ApiResult<List<PriceServiceTypeDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取价格服务类型列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取价格服务类型列表时发生异常");
                return new ApiResult<List<PriceServiceTypeDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取价格服务类型列表失败：" + ex.Message
                };
            }
        }

        // 根据科室ID获取科室名称（实际应该从科室表获取）
        private string GetDepartmentName(int deptId)
        {
            // 这里应该查询科室表，为简化示例直接返回
            return "科室" + deptId;
        }
    }
} 